﻿#include "semaphore.h"
#include <limits.h>
#include "remote_obj_error.h"
using namespace RemoteObj;
Semaphore::Semaphore(int32_t init_size)
{
    if (init_size < 0)
    {
        init_size = 0;
    }
    _sem = CreateSemaphore(NULL, init_size, LONG_MAX, NULL);
}

Semaphore::~Semaphore()
{
    if (NULL != _sem)
    {
        BOOL ret = CloseHandle(_sem);
        if (0 != ret)
        {
            _sem = NULL;
        }
    }
}

int32_t Semaphore::wait(uint32_t millisecond)
{
    if (NULL == _sem)
    {
        return E_REMOTEOBJ_NULL_POINTER;
    }

    DWORD ret = WaitForSingleObject(_sem, millisecond);
    if (WAIT_OBJECT_0 == ret || WAIT_ABANDONED == ret)
    {
        return 0;
    }
    else if (WAIT_TIMEOUT == ret)
    {
        return E_REMOTEOBJ_TIMEOUT;
    }
    else
    {
        return E_REMOTEOBJ_SYSERROR;
    }
}

int32_t Semaphore::signal()
{
    BOOL ret = FALSE;

    if (NULL != _sem)
    {
        ret = ReleaseSemaphore(_sem, 1, NULL);
    }
    return (0 != ret ? 0 : E_REMOTEOBJ_SYSERROR);

}

